package com.smartHome.controller;

import com.smartHome.pojo.entity.Result;
import com.smartHome.pojo.vo.WeatherVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.json.JSONObject;
import org.json.JSONArray;

@RestController
public class WeatherController {

    @Autowired
    @Qualifier("weatherRestTemplate")
    private org.springframework.web.client.RestTemplate restTemplate;

    //高德天气API获取南海区的天气
    private static final String WEATHER_API_URL = "https://restapi.amap.com/v3/weather/weatherInfo?city=440605&key=9bb17b2b496b6f1e91598db9bc3b1a28";

    @GetMapping("/weather")
    public Result<WeatherVO> getWeather() {
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(WEATHER_API_URL, String.class);
            String jsonResponse = response.getBody();

            JSONObject jsonObject = new JSONObject(jsonResponse);
            JSONArray lives = jsonObject.getJSONArray("lives");
            JSONObject weatherData = lives.getJSONObject(0);

            //封装城市、天气、温度
            WeatherVO weatherVO = new WeatherVO();
            weatherVO.setCity(weatherData.getString("city"));
            weatherVO.setWeather(weatherData.getString("weather"));
            weatherVO.setTemperature(weatherData.getString("temperature"));

            return Result.success(weatherVO);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取天气信息失败");
        }
    }
}
